<!-- eslint-disable unused-imports/no-unused-vars -->
<script setup lang="ts">
import type { SummaryReport } from "../apis/type"
import { ElMessage } from "element-plus"
import { onMounted, reactive, ref } from "vue"
import {
  getSummaryReportDetailApi,
  getSummaryReportsApi,
  reviewSummaryReportApi
} from "../apis/report"

// 响应式数据
const loading = ref(false)
const reportList = ref<SummaryReport[]>([])
const dialogVisible = ref(false)
const reviewFormRef = ref()
const currentReportId = ref(0)
const currentReport = ref<SummaryReport>({
  id: 0,
  taskId: 0,
  studentId: 0,
  studentName: "",
  positionName: "",
  cycleType: "weekly",
  workContents: [],
  achievements: "",
  achievementFiles: [],
  problems: [],
  nextPlan: "",
  status: "pending"
})

// 搜索表单
const searchForm = reactive({
  studentName: "",
  major: "",
  status: ""
})

// 审核表单
const reviewForm = reactive({
  status: "approved" as "approved" | "rejected",
  score: 3,
  comment: "",
  suggestion: ""
})

// 审核表单验证规则
const reviewRules = computed(() => ({
  score: [
    { required: reviewForm.status === "approved", message: "请评分", trigger: "change" }
  ],
  comment: [
    { required: true, message: "请填写审核意见", trigger: "blur" }
  ]
}))

// 获取评分标签
function getScoreLabel(score?: number) {
  const scoreMap: Record<number, string> = {
    1: "不合格",
    2: "合格",
    3: "中等",
    4: "良好",
    5: "优秀"
  }
  return scoreMap[score || 0] || "未评分"
}

// 加载报告列表
async function loadReportList() {
  loading.value = true
  try {
    const { code, data } = await getSummaryReportsApi({
      currentPage: 1,
      size: 10,
      ...searchForm
    })
    if (code === 200 && data) {
      reportList.value = data.list
    }
  } catch (_error) {
    ElMessage.error("获取报告列表失败")
  } finally {
    loading.value = false
  }
}

// 处理搜索
function handleSearch() {
  loadReportList()
}

// 重置搜索
function resetSearch() {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key as keyof typeof searchForm] = ""
  })
  loadReportList()
}

// 处理审核报告
async function handleReviewReport(reportId: number) {
  currentReportId.value = reportId
  try {
    const { code, data } = await getSummaryReportDetailApi(reportId)
    if (code === 200 && data) {
      currentReport.value = data
      // 如果是待审核状态，重置审核表单
      if (data.status === "pending") {
        reviewForm.status = "approved"
        reviewForm.score = 3
        reviewForm.comment = ""
        reviewForm.suggestion = ""
      }
      dialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error("获取报告详情失败")
  }
}

// 提交审核
async function submitReview() {
  try {
    await reviewFormRef.value?.validate()

    loading.value = true
    const response = await reviewSummaryReportApi(currentReportId.value, {
      status: reviewForm.status,
      score: reviewForm.status === "approved" ? reviewForm.score : undefined,
      comment: reviewForm.comment,
      suggestion: reviewForm.suggestion
    })

    if (response.code === 200) {
      ElMessage.success("审核成功")
      dialogVisible.value = false
      loadReportList() // 重新加载报告列表
    }
  } catch (error) {
    ElMessage.error("审核失败")
  } finally {
    loading.value = false
  }
}

// 初始加载
onMounted(() => {
  loadReportList()
})
</script>

<template>
  <div class="summary-review-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>总结审核</span>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="学生姓名">
          <el-input v-model="searchForm.studentName" placeholder="输入学生姓名" />
        </el-form-item>
        <el-form-item label="专业">
          <el-select v-model="searchForm.major" placeholder="选择专业" clearable style="width: 200px;">
            <el-option label="计算机科学与技术" value="cs" />
            <el-option label="软件工程" value="se" />
            <el-option label="数据科学与大数据技术" value="data-science" />
            <el-option label="电子信息工程" value="ee" />
            <el-option label="通信工程" value="comm" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px;">
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            搜索
          </el-button>
          <el-button @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 报告列表 -->
      <div v-loading="loading" class="report-list">
        <el-table :data="reportList" style="width: 100%">
          <el-table-column prop="studentName" label="学生姓名" min-width="100" />
          <el-table-column prop="positionName" label="实习岗位" min-width="150" />
          <el-table-column prop="cycleType" label="类型" min-width="80">
            <template #default="scope">
              <el-tag :type="scope.row.cycleType === 'weekly' ? 'primary' : 'success'">
                {{ scope.row.cycleType === 'weekly' ? '周报' : '月报' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="submittedAt" label="提交时间" min-width="150" />
          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 'pending'" type="info">
                待审核
              </el-tag>
              <el-tag v-else-if="scope.row.status === 'approved'" type="success">
                已通过
              </el-tag>
              <el-tag v-else-if="scope.row.status === 'rejected'" type="danger">
                已驳回
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="120" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleReviewReport(scope.row.id)"
              >
                {{ scope.row.status === 'pending' ? '审核' : '查看' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 审核报告对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentReport.status === 'pending' ? '审核总结报告' : '查看总结报告'"
      width="80%"
      :close-on-click-modal="false"
    >
      <!-- 学生报告内容 -->
      <div class="report-content">
        <h3>报告基本信息</h3>
        <el-descriptions border :column="2" :model="currentReport" size="small">
          <el-descriptions-item label="学生姓名">
            {{ currentReport.studentName }}
          </el-descriptions-item>
          <el-descriptions-item label="实习岗位">
            {{ currentReport.positionName }}
          </el-descriptions-item>
          <el-descriptions-item label="周期类型">
            {{ currentReport.cycleType === 'weekly' ? '周报' : '月报' }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ currentReport.submittedAt }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :column-span="2">
            {{ currentReport.remark || '-' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentReport.overdueReason" label="逾期理由" :column-span="2">
            {{ currentReport.overdueReason }}
          </el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px;">
          工作内容
        </h3>
        <div v-if="currentReport.workContents && currentReport.workContents.length > 0" class="content-section">
          <div v-for="(item, index) in currentReport.workContents" :key="index" class="content-item">
            <span class="content-type">{{ item.type }}：</span>
            <span class="content-text">{{ item.content }}</span>
          </div>
        </div>
        <div v-else class="empty-text">
          无
        </div>

        <h3 style="margin-top: 20px;">
          工作成果
        </h3>
        <div class="content-section">
          <p>{{ currentReport.achievements || '-' }}</p>
          <div v-if="currentReport.achievementFiles && currentReport.achievementFiles.length > 0" class="file-list">
            <el-link
              v-for="(file, index) in currentReport.achievementFiles"
              :key="index"
              :href="file"
              target="_blank"
              type="primary"
            >
              附件{{ index + 1 }}
            </el-link>
          </div>
        </div>

        <h3 style="margin-top: 20px;">
          问题与解决方法
        </h3>
        <div v-if="currentReport.problems && currentReport.problems.length > 0" class="content-section">
          <div v-for="(item, index) in currentReport.problems" :key="index" class="problem-item">
            <p><strong>问题{{ index + 1 }}：</strong>{{ item.problem }}</p>
            <p><strong>解决方法：</strong>{{ item.solution }}</p>
          </div>
        </div>
        <div v-else class="empty-text">
          无
        </div>

        <h3 style="margin-top: 20px;">
          下周/月计划
        </h3>
        <div class="content-section">
          <p>{{ currentReport.nextPlan || '-' }}</p>
        </div>

        <h3 style="margin-top: 20px;">
          审核结果
        </h3>
        <el-descriptions v-if="currentReport.status !== 'pending'" border :column="2" size="small">
          <el-descriptions-item label="审核状态">
            <el-tag :type="currentReport.status === 'approved' ? 'success' : 'danger'">
              {{ currentReport.status === 'approved' ? '已通过' : '已驳回' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentReport.score" label="评分">
            {{ getScoreLabel(currentReport.score) }}
          </el-descriptions-item>
          <el-descriptions-item label="审核意见" :column-span="2">
            {{ currentReport.comment || '-' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentReport.suggestion" label="附加建议" :column-span="2">
            {{ currentReport.suggestion }}
          </el-descriptions-item>
          <el-descriptions-item label="审核时间">
            {{ currentReport.reviewedAt }}
          </el-descriptions-item>
          <el-descriptions-item label="审核老师">
            {{ currentReport.reviewerName }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 审核表单 -->
      <div v-if="currentReport.status === 'pending'" class="review-form">
        <el-divider content-position="left">
          审核评分与反馈
        </el-divider>
        <el-form ref="reviewFormRef" :model="reviewForm" :rules="reviewRules" label-width="100px">
          <el-form-item label="审核结果" required>
            <el-radio-group v-model="reviewForm.status">
              <el-radio label="approved">
                通过
              </el-radio>
              <el-radio label="rejected">
                不通过
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            v-if="reviewForm.status === 'approved'"
            label="评分"
            prop="score"
            required
          >
            <el-rate v-model="reviewForm.score" :texts="['不合格', '合格', '中等', '良好', '优秀']" show-text />
          </el-form-item>

          <el-form-item label="审核意见" prop="comment" required>
            <el-input
              v-model="reviewForm.comment"
              type="textarea"
              :rows="3"
              placeholder="请输入审核意见"
            />
            <div v-if="reviewForm.status === 'approved'" class="form-hint">
              提示：请给出简短的评语，如"成果清晰，继续保持"
            </div>
            <div v-else class="form-hint">
              提示：请分点说明修改理由，如"成果未量化，需补具体数据"
            </div>
          </el-form-item>

          <el-form-item label="附加建议">
            <el-input
              v-model="reviewForm.suggestion"
              type="textarea"
              :rows="2"
              placeholder="可选，如：多学XX技能提升效率"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">
          关闭
        </el-button>
        <el-button
          v-if="currentReport.status === 'pending'"
          type="primary"
          @click="submitReview"
        >
          提交审核
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.summary-review-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.report-content {
  max-height: 600px;
  overflow-y: auto;
}

.content-section {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.content-item {
  margin-bottom: 5px;
  padding: 5px 0;
}

.content-type {
  font-weight: bold;
  color: #606266;
}

.content-text {
  color: #303133;
}

.problem-item {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
}

.problem-item:last-child {
  margin-bottom: 0;
}

.empty-text {
  color: #909399;
  font-style: italic;
  padding: 10px;
}

.file-list {
  margin-top: 10px;
}

.file-list .el-link {
  margin-right: 15px;
}

.review-form {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
</style>
